package com.wmyg.antifake.service.impl;

import com.wmyg.antifake.entity.BkUser;
import com.wmyg.antifake.entity.Factory;
import com.wmyg.antifake.repository.BkUserRepository;
import com.wmyg.antifake.repository.FactoryRepository;
import com.wmyg.antifake.service.FactoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 王卓逸
 * @program TODO
 * @description TODO
 * @create 2019-05-20
 */
@Service
public class FactoryServiceImpl implements FactoryService {

    @Autowired
    FactoryRepository factoryRepository;

    @Autowired
    BkUserRepository bkUserRepository;

    @Override
    public Boolean saveFactory(Factory factory, String username) {
        BkUser bkUser = bkUserRepository.findByUsername(username);
        if (null != bkUser && null != bkUser.getCompany()) {
            factory.setCompany(bkUser.getCompany());
            if (null != factory.getFactoryId()) {
                Factory factoryOld = factoryRepository.findByFactoryId(factory.getFactoryId());
                factory.setCreateTime(factoryOld.getCreateTime());
            }
            factoryRepository.save(factory);
            return true;
        }
        return false;
    }

    @Override
    public List<Factory> getFactoryList(String username) {
        BkUser bkUser = bkUserRepository.findByUsername(username);
        if (null != bkUser && null != bkUser.getCompany()) {
            return factoryRepository.findByCompanyOrderByCreateTimeDesc(bkUser.getCompany());
        } else {
            return null;
        }
    }

    @Override
    public Page<Factory> getFactoryPage(String username, Integer index) {
        BkUser bkUser = bkUserRepository.findByUsername(username);
        if (null != bkUser && null != bkUser.getCompany()) {
            return factoryRepository.findByCompanyOrderByCreateTimeDesc(bkUser.getCompany(), PageRequest.of(index, 10));
        } else {
            return null;
        }
    }

    @Override
    public Page<Factory> getFactoryPage(String username, Integer index, String factoryName) {
        BkUser bkUser = bkUserRepository.findByUsername(username);
        if (null != bkUser && null != bkUser.getCompany()) {
            return factoryRepository.findByCompanyAndFactoryNameLikeOrderByCreateTimeDesc(bkUser.getCompany(), "%" + factoryName + "%", PageRequest.of(index, 10));
        } else {
            return null;
        }
    }

    @Override
    public Factory findByFactoryId(Integer factoryId) {
        return factoryRepository.findByFactoryId(factoryId);
    }
}
